package com.qingzhuge.member.service.impl;

import com.qingzhuge.cache.CacheChannel;
import com.qingzhuge.exception.ValidatorException;
import com.qingzhuge.interfaces.IPersistable;
import com.qingzhuge.member.dao.MallImageTextDao;
import com.qingzhuge.member.entity.SysImageText;
import com.qingzhuge.member.enums.EnumPublishType;
import com.qingzhuge.member.enums.EnumRoleType;
import com.qingzhuge.member.service.IMalImageTextService;
import com.qingzhuge.member.utils.QueryHelp;
import com.qingzhuge.pageview.service.ISysPageViewService;
import com.qingzhuge.service.BasePkLongServiceImpl;
import com.qingzhuge.utils.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

import static com.qingzhuge.entity.BaseBean.PAGE_NO;
import static com.qingzhuge.entity.BaseBean.PAGE_SIZE;

/**
 * @author : zero.xiao
 * @description : 图文
 * @date :2018/6/12 0012 下午 17:25
 * @modified :
 * @since : 1.0.0
 */
@Service
public class MallImageTextServiceImpl extends BasePkLongServiceImpl<MallImageTextDao, SysImageText>
        implements IMalImageTextService {

    @Resource
    private ISysPageViewService pageViewService;

    @Autowired
    protected CacheChannel cache;

    @Override
    public List<SysImageText> selectType(EnumPublishType type, Integer deleted) {
        String key = String.format("selectType:%s", type);
        List<SysImageText> cache = getCache("imageTextService",key);
        if (null == cache || cache.isEmpty()) {
            cache = baseDao.findByShowCategoryAndDeleted(type, deleted);
            saveCache(key, cache);
        }
        return cache;
    }

    @Override
    public List<SysImageText> selectEffectiveAll(Integer deleted) {
        String key = String.format("selectEffectiveAll:%s", deleted);
        List<SysImageText> cache = getCache("imageTextService",key);
        if (null == cache || cache.isEmpty()) {
            cache = baseDao.findByDeleted(deleted);
            saveCache(key, cache);
        }
        return cache;
    }

    @Override
    public SysImageText selectEffectiveById(Long id, Integer deleted) {
        String key = String.format("selectEffectiveById:%s", id + deleted);
        SysImageText cache = getCache(key);
        if (null == cache) {
            cache = baseDao.findByIdAndDeleted(id, deleted);
            saveCache(key, cache);
        }
        return cache;
    }

    @Override
    public List<SysImageText> saveAll(List<SysImageText> imagetext) {
        return baseDao.saveAll(imagetext);
    }

    @Override
    public SysImageText add(SysImageText entity, Long userId) {
        //角色类型
        if (entity.getShowCategory() == EnumPublishType.SOFT_ARTICLE) {
            entity.setRoleCategory(EnumRoleType.USER);
        } else if (entity.getShowCategory() == EnumPublishType.INFO) {
            entity.setRoleCategory(EnumRoleType.USER);
        } else if (entity.getShowCategory() == EnumPublishType.INFORM) {
            entity.setRoleCategory(EnumRoleType.STORE);
        } else if (entity.getShowCategory() == EnumPublishType.REQUIRE) {
            entity.setRoleCategory(EnumRoleType.STORE);
        }
        entity.setDeleted(SysImageText.DELETE_NORMEL);
        if (null == entity.getStatus()) {
            entity.setStatus(SysImageText.STATUS_SHOW);
        }
        entity.setCreateBy(userId);
        return super.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysImageText getDetails(Long id, Boolean userSide) {
        SysImageText byId = selectEffectiveById(id, SysImageText.DELETE_NORMEL);
        if (null == byId) {
            throw new ValidatorException("数据不存在");
        }
        if (userSide) {
            pageViewService.updateVpByModuleAndObjId(byId.getClass().getSimpleName(), id.toString());
        }
        int vp = pageViewService.findVpByModuleAndObjId(byId.getClass().getSimpleName(), id.toString());
        byId.setVp(vp);
        return byId;
    }

    /**
     * 根据实体参数分页查询
     */
    @Override
    public PageUtil<SysImageText> querys(SysImageText entity, boolean isType) {
        PageUtil<SysImageText> query = getMallImageTextPageUtil(entity, isType);
        query.getContent().forEach(imageText -> {
            int vpByModuleAndObjId = pageViewService.findVpByModuleAndObjId(imageText.getClass().getSimpleName(), imageText.getId().toString());
            imageText.setVp(vpByModuleAndObjId);
        });
        return query;
    }

    private PageUtil<SysImageText> getMallImageTextPageUtil(SysImageText entity, boolean isType) {
        if (null == entity.getPage() || entity.getPage() < 0) {
            entity.setPage(PAGE_NO);
        } else {
            entity.setPage(entity.getPage() - 1);
        }
        if (null == entity.getSize() || entity.getSize() < 1) {
            entity.setSize(PAGE_SIZE);
        }
        Sort sort = Sort.by(Sort.Direction.DESC, IPersistable.ID_FIELDS);
        PageRequest page = PageRequest.of(entity.getPage(), entity.getSize(), sort);
        if (StringUtils.isNotBlank(entity.getOrderByField())) {
            boolean existField = QueryHelp.isExistField(entity.getClass(), entity.getOrderByField());
            if (existField) {
                if (null != entity.getAsc() && entity.getAsc()) {
                    sort = Sort.by(Sort.Direction.ASC, entity.getOrderByField());
                }
                page = PageRequest.of(entity.getPage(), entity.getSize(), sort);
            }
        }
        Page<SysImageText> pageList;
        Specification<SysImageText> specification = QueryHelp.setQueryPageForSpecification(entity, isType);
        pageList = baseDao.findAll(specification, page);
        if (pageList.getTotalElements() > 0) {
            new Runnable() {
                @Override
                public void run() {
                    List<SysImageText> list = pageList.getContent();
                    log.debug("设置查询缓存 size:{}", pageList.getSize());
                    for (SysImageText t : list) {
                        saveCache(t);
                    }
                }
            };
        }
        return QueryHelp.pageOf(pageList);
    }


}
